# stock_parser.py
import requests
import logging
import time
from typing import List, Dict, Optional
from dataclasses import dataclass
from config import MONITOR_CONFIG

logger = logging.getLogger(__name__)

@dataclass
class StockData:
    """股票数据"""
    symbol: str
    name: str
    current_price: float
    change_amount: float
    change_percent: float
    high: float
    low: float
    volume: str
    turnover: str
    time: str

class StockParser:
    """股票数据解析器"""
    
    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        })
    
    def fetch_stock_data(self, symbols: List[str]) -> Optional[str]:
        """
        获取股票数据
        
        Args:
            symbols: 股票代码列表
            
        Returns:
            str: 原始数据字符串
        """
        url = f"https://qt.gtimg.cn/q={','.join(symbols)}"
        
        for attempt in range(MONITOR_CONFIG.max_retries):
            try:
                logger.debug(f"请求股票数据: {url}")
                response = self.session.get(url, timeout=10)
                response.raise_for_status()
                
                if response.text:
                    return response.text
                else:
                    logger.warning(f"第 {attempt + 1} 次请求返回空数据")
                    
            except requests.exceptions.RequestException as e:
                logger.warning(f"第 {attempt + 1} 次请求失败: {e}")
                
            if attempt < MONITOR_CONFIG.max_retries - 1:
                time.sleep(MONITOR_CONFIG.retry_delay)
        
        logger.error(f"所有 {MONITOR_CONFIG.max_retries} 次请求都失败了")
        return None
    
    def parse_stock_data(self, raw_data: str, stock_configs: List) -> List[StockData]:
        """
        解析股票数据
        
        Args:
            raw_data: 原始数据字符串
            stock_configs: 股票配置列表
            
        Returns:
            List[StockData]: 解析后的股票数据列表
        """
        if not raw_data:
            return []
        
        stock_data_list = []
        stock_data_array = raw_data.split(';')
        
        for stock_data in stock_data_array:
            if not stock_data.strip():
                continue
            
            try:
                # 解析数据格式: v_sh600519="1~贵州茅台~600519~1942.00~..."
                if '=' not in stock_data:
                    continue
                    
                symbol_part, data_part = stock_data.split('=', 1)
                symbol = symbol_part.replace('v_', '').strip()
                
                # 清理数据部分
                data_body = data_part.strip().strip('"').strip("'")
                if not data_body:
                    continue
                
                fields = data_body.split('~')
                if len(fields) < 40:
                    continue
                
                # 查找对应的股票配置
                stock_config = next(
                    (config for config in stock_configs if config.symbol == symbol), 
                    None
                )
                if not stock_config:
                    continue
                
                # 创建股票数据对象
                stock = StockData(
                    symbol=symbol,
                    name=stock_config.name,
                    current_price=self._safe_float(fields[3]),
                    change_amount=self._safe_float(fields[31]),
                    change_percent=self._safe_float(fields[32]),
                    high=self._safe_float(fields[33]),
                    low=self._safe_float(fields[34]),
                    volume=fields[36] or '0',
                    turnover=fields[37] or '0',
                    time=fields[30] or ''
                )
                
                stock_data_list.append(stock)
                logger.debug(f"解析股票数据: {stock.name} - 价格: {stock.current_price}")
                
            except Exception as e:
                logger.error(f"解析股票数据失败: {stock_data}, 错误: {e}")
                continue
        
        return stock_data_list
    
    def _safe_float(self, value: str) -> float:
        """安全转换字符串为浮点数"""
        try:
            return float(value) if value else 0.0
        except (ValueError, TypeError):
            return 0.0


# 创建全局解析器实例
stock_parser = StockParser()